/*
 * Created on 27/08/2006
 *
 */
package tur.br.moradadosol.view.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import tur.br.moradadosol.control.HospedeControl;
import tur.br.moradadosol.control.UserAutentication;
import tur.br.moradadosol.view.form.HospedeForm;

/**
 * @author Ramon F. Garcia
 *
 */
public class ProcuraHospedeAction extends Action {
	
	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {
			
		HttpSession session = request.getSession();

		if(!UserAutentication.isUserAutenticated(session)) {
			return mapping.findForward("login");
		}
		
		ActionMessages errors = new ActionMessages();
	
		HospedeForm Form = (HospedeForm) form;
		
		HospedeControl hospedeControl = 
			(HospedeControl) session.getAttribute("hospedeControl");
		if(hospedeControl == null) {
			hospedeControl = new HospedeControl();
		}
		
		try {
			if(Form.getPesquisar().length() > 0) {
				Form.setHospedes(hospedeControl.getHospedesByNome(
					Form.getNomepesquisa()));
			}
			else if(Form.getVoltar().length() > 0) {
				return mapping.findForward((String)
					session.getAttribute("pagina"));
			}
			else if(Form.getCadastrar().length() > 0) {
				return mapping.findForward("hospede");
			}
			else {
				Form.setNome("");
			}
		} catch (Exception e) {
			errors.add("name", new ActionMessage("error.exception"));
		}
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
		}
		
		request.setAttribute("pagina", session.getAttribute("pagina"));
		
		return mapping.getInputForward();
	}

}
